const app = getApp()
const db = wx.cloud.database();

let filePath = null;
let currentType = "";
let desc = "";

Page({

  data: {
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    userInfo: "",
    hasUserInfo: false,
    wdfImgArr: [],
    wdfVideoArr: [],
    imgID: "",
    videoID: "",
    IMGTitle: '',
    VideoTitle: '',
    tempImgUrl: '',
    tempvideoUrl: '',

    // 声明一个tempObject存放用户个人中心的游戏数据
    UserGameInfo: {},
  },


  getUserGameInfo(){
    db.collection("userInfo").where({
      _openid: app.currentUserOpenid
    }).get().then(res=>{
      this.setData({
        UserGameInfo: res.data[0]
      })
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getUserGameInfo()
  },

  getUserOpenId(){
    wx.cloud.callFunction({
      name: 'getOpenId',
      complete: res => {
        app.currentUserOpenid = res.result.openid

        db.collection("userResources").where({
          _openid: app.currentUserOpenid, 
          type: 'wdfImg'
        }).get().then(res2=>{
          let tempImgArr = []
          res2.data.forEach(
            (item,index)=>{
              tempImgArr.push(item)
            }
          )
          this.setData({
            wdfImgArr: tempImgArr
          })
          // console.log("wdfImgArr 用来渲染",this.data.wdfImgArr);
        })

        db.collection("userResources").where({
          _openid: app.currentUserOpenid, 
          type: 'wdfVideo'
        }).get().then(res3=>{
          let tempVideoArr = []
          // console.log("res3.data",res3.data);
          res3.data.forEach(
            (item,index)=>{
              tempVideoArr.push(item)
            }
          )
          this.setData({
            wdfVideoArr: tempVideoArr
          })
          // console.log("wdfVideoArr 用来渲染",this.data.wdfVideoArr);
        })
      }
    })
  },

  judgeOpenid(){
    db.collection("userInfo").where({
      _openid: app.currentUserOpenid, 
    }).get().then(res=>{
        if (res.data.length !=0) {
          app.collectionOpenid = true
          console.log("云数据库有当前用户信息，允许用户进入“我的”页面");
          wx.switchTab({
            url: '../users/users',
          })
        }
        if(!app.collectionOpenid){
          console.log("用户未授权登录，退回授权页面");
          wx.redirectTo({
          url: '../authorization/authorization',
          })
        }
    })
  },

  /**
   * 生命周期函数--监听页面显示
  */
  onShow: function () {
    // 调用查询用户openid的函数
    this.getUserOpenId()
    // 调用判断用户openid和集合里的openid是否相符
    this.judgeOpenid()
  },

  // 官方资讯按钮————跳转首页
  onclick1(){
    wx.switchTab({
      url: '../news/news'
    })
  },

  // 动态发布按钮————跳转到当前用户所发过的动态页面
  onclick2(){
    wx.redirectTo({
      url: '../showBox/likes/likes',
    })
  },

  // 时装库按钮————跳转时装库
  onclick3(){
    wx.switchTab({
      url: '../show/show'
    })
  },

  change_photo() {
    this.setData({
      display1: "flex",
      display2: "none",
      color1: "#000",
      bgcolor1: "rgb(236, 240, 244)",
      color2: "#ccc",
      bgcolor2: "#fff",
      fw1: "800",
      fw2: "300",
    })
  },

  change_video() {
    this.setData({
      display2: "flex",
      display1: "none",
      color2: "#000",
      bgcolor2: "rgb(236, 240, 244)",
      color1: "#ccc",
      bgcolor1: "#fff",
      fw2: "800",
      fw1: "300",
    })
  },

  // 显示个性签名窗口
  showPer_box() {
    this.setData({
      showPer: "block",
    })
  },

  // 隐藏个性签名窗口
  hidePer_box() {
    this.setData({
      showPer: "none",
    })
  },

  // 隐藏上传图片/视频的显隐、悬空盒子窗口
  hideImg_box() {
    this.setData({
      loadImgBox: "none",
    })
  },

  hideVideo_box(){
    this.setData({
      loadVideoBox: "none",
    })
  },

  // 用户点击确定按钮——提交个性签名
  btnSubmit(res){
    wx.showLoading({
      title: '修改中...'
    })
    db.collection("userInfo").where({
      _openid: app.currentUserOpenid
    }).update({
      data:{
        signature: res.detail.value.perSign
      }
    }).then(res=>{
      console.log("个性签名修改成功！",res);
    })
    wx.hideLoading()
    this.onLoad()
  },

  // 图片和视频 上传/删除按钮点击事件
  cloudFile(filename,imgpath){
    wx.showLoading({
      title: '上传中...'
    })
    wx.cloud.uploadFile({
      cloudPath: filename+".jpg",
      filePath: imgpath
    }).then(res=>{
      filePath = res.fileID
      this.setData({
        hidetext: "block",
        hideimg: "none",
        tempImgUrl: filePath,
      })
      
    })
    wx.hideLoading()
  },

  cloudFile2(filename,Videopath){
    wx.showLoading({
      title: '上传中...'
    })
    wx.cloud.uploadFile({
      cloudPath: filename+".mp4",
      filePath: Videopath
    }).then(res=>{
      filePath = res.fileID
      this.setData({
        hidevideo: "block",
        hideimg: "none",
        tempvideoUrl: filePath,
      })
    })
    wx.hideLoading()
  },

  // 造一个将图片/视频的在存储中的地址上传到集合表里的函数
  onloadFilesToColl(fileType,des){
    db.collection("userResources").add({
      data:{
        wdfImgUrl: filePath,
        type: fileType,
        description: des,
        wxkey: Math.random()*100000
      }
    }).then((res)=>{
      // console.log(res._id);
      db.collection("userResources").doc(res._id).get().then(res2=>{
        console.log(res2.data);
        let tempImgarr = this.data.wdfImgArr
        tempImgarr.push(res2.data)
        this.setData({
          wdfImgArr: tempImgarr
        })
        console.log("图片已上传");
      })
    })
  },

  onloadFilesToColl2(fileType,des){
    db.collection("userResources").add({
      data:{
        wdfVideoUrl: filePath,
        type: fileType,
        description: des,
        wxkey: Math.random()*100000
      }
    }).then((res)=>{
      db.collection("userResources").doc(res._id).get().then(res2=>{
        console.log(res2.data);
        let tempVideoarr = this.data.wdfVideoArr
        tempVideoarr.push(res2.data)
        this.setData({
          wdfVideoArr: tempVideoarr
        })
        console.log("视频已上传");
      })
    })
  },

  // 上传图片
  shangchuan(){
    wx.chooseImage({
      count: 1,
      success:res=>{
        filePath = res.tempFilePaths[0] + ""  //获得图片的临时地址
        let fileName = Date.now();   // 给上传到存储里的图片一个以时间戳定义的名字
        this.cloudFile(fileName,filePath)
      }
    })
  },

  // 上传视频
  shangchuan2(){
    wx.chooseVideo({
      sourceType: ['album','camera'],
      maxDuration: 60,
      camera: 'back',
      success:res=>{
        filePath = res.tempFilePath + ""  //获得图片的临时地址
        let fileName = Date.now();   // 给上传到存储里的图片一个以时间戳定义的名字
        this.cloudFile2(fileName,filePath)
      }
    })
  },


  // 用户点击确定触发————图片
  IMGSubmit(res){
    this.setData({
      hidetext: "none",
      hideimg: "block",
      loadImgBox: "none",
      IMGTitle: ''
    })
    currentType = "wdfImg"
    desc = res.detail.value.onloadIMG
    this.onloadFilesToColl(currentType,desc)
  },

  // 用户点击确定触发————视频
  IMGSubmit2(res){
    this.setData({
      hidetext: "none",
      hideimg: "block",
      loadVideoBox: "none",
      VideoTitle: ''
    })
    currentType = "wdfVideo"
    desc = res.detail.value.onloadIMG2
    this.onloadFilesToColl2(currentType,desc)
  },

  // 点击了上传图片的加号
  imgUpload(){
    console.log("用户想要上传图片");
    this.setData({
      loadImgBox: "block"
    })
  },

  getdomId(e){
    // console.log(e.target);
    this.setData({
      imgID: e.target.dataset.imgid
    })
    console.log("当前选中的元素imgID",this.data.imgID);
  },

  getdomId2(e){
    this.setData({
      videoID: e.target.dataset.videoid
    })
    console.log("当前选中的元素videoID",this.data.videoID);
  },

  // 删除图片
  imgDelete(){
    if (!this.data.imgID) {
      wx.showToast({
        title: '请选择图片',
        icon: 'error'
      })
    }else {
      wx.showModal({
        title: '提示',
        content: '确定要删除该图片吗？',
        success: (res) => {
          if (res.confirm) {
            db.collection('userResources').doc(this.data.imgID).remove({
              success: function(res) {
                console.log("图片删除成功");
                wx.showToast({
                  title: '图片已被删除',
                })
              }
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }
  },

  // 上传视频
  videoUpload(){
    console.log("用户想要上传视频");
    this.setData({
      loadVideoBox: "block"
    })
  },

  // 删除视频
  videoDelete(){
    if (!this.data.videoID) {
      wx.showToast({
        title: '请选择视频',
        icon: 'error'
      })
    }else {
      wx.showModal({
        title: '提示',
        content: '确定要删除该视频吗？',
        success: (res) => {
          if (res.confirm) {
            db.collection('userResources').doc(this.data.videoID).remove({
              success: function(res) {
                console.log("视频删除成功");
                wx.showToast({
                  title: '视频已被删除',
                })
              }
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
      
    }
  },
})